package com.springsecurity.config;

import com.springsecurity.Service.UserService;
import com.springsecurity.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;

@EnableWebSecurity
public class SecurityConfig extends  WebSecurityConfigurerAdapter {


@Autowired
private UserService userService;

    //自定义用户认证（内存方式）

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws
            Exception {
//        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
//        auth.userDetailsService(userService).passwordEncoder(encoder);
        //填写下列数据 可以在测试类中通过如下代码填入用户信息
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication().passwordEncoder(bCryptPasswordEncoder).withUser("common").password(bCryptPasswordEncoder.encode("123")).roles("common")
                .and()
                .withUser("vip").password(bCryptPasswordEncoder.encode("123")).roles("vip").roles("common");

}
    //自定义权限控制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/index").permitAll()
                .antMatchers("/common/**").hasRole("common")
                .antMatchers("/vip/**").hasRole("vip")
                .anyRequest().authenticated();

        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/index")
                .failureUrl("/login?error");
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index");
        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200);
    }
    }
